import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { ApiService } from 'src/app/core/api';
import { NzMessageService } from 'ng-zorro-antd';
import { Title } from '@angular/platform-browser';
import { TranslateService } from '@ngx-translate/core';
import { I18nService } from 'src/app/core/i18n/i18n.service';
import { en_US, zh_CN,ja_JP, NzI18nService } from 'ng-zorro-antd/i18n';
@Component({
	selector: 'app-login',
	templateUrl: './login.component.html',
	styleUrls: ['./login.component.scss'],
})
export class LoginComponent implements OnInit {
	loginForm: FormGroup;
	imageVerifyCodeId;
	e;
	lang;
	ngOnInit() {
		this.loginForm = this.fb.group({
			loginId: [null, [Validators.required]],
			loginPw: [null, [Validators.required]],
			imageVerifyCodeId: [null],
			imageCode: [null, [Validators.required]],
		});
		this.service.post('生成图形验证码唯一id', {}).then(res => {
			this.imageVerifyCodeId = res['data']['imageVerifyCodeId'];
			this.loginForm.patchValue({ imageVerifyCodeId: this.imageVerifyCodeId });
		});
	}
	submit() {
		if (this.loginForm.valid) {
			this.service
				.post('登录', this.loginForm.value)
				.then((res: any) => {
					sessionStorage.setItem('token', res.data.token);
					sessionStorage.setItem('user', JSON.stringify({ auths: res.data.auths, loginId: res.data.loginId }));
					this.router.navigate(['basicSetting/orders']);
				})
				.catch(res => {
					this.message.error(res.data.message);
				});
		}
	}
	onChangImgCode() {
		this.e = Math.random() * 10000;
	}
	changeLang(e) {
		this.i18n.changeLang(e);
		localStorage.setItem('lang',e);
		switch(e){
			case 'zh':
				this.nzI18n.setLocale(zh_CN);
				break;
			case 'jp':
				this.nzI18n.setLocale(ja_JP);
				break;
			case 'en':
				this.nzI18n.setLocale(en_US);
				break;
		}
		
	}
	constructor(private nzI18n:NzI18nService,private i18n: I18nService,private fb: FormBuilder, private router: Router, private service: ApiService, private message: NzMessageService, private _title:Title,private translate:TranslateService) {
		this.lang = {lang: localStorage.getItem('lang') || 'zh'};
    	this.translate.onLangChange.subscribe(params => {
			console.log('language',params);
			this.lang = params;
		});
		this.i18n.get(['title']).subscribe(res=>{
			this._title.setTitle(res.title);
		})
	}
}
